<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="parent">
        <div class="children">
            <div class="children-1">
                <div class="children-1-1"></div>
            </div>
            <div class="children-2">
                <div class="children-2-1"></div>
            </div>
            <div class="children-3">
                <div class="children-3-1"></div>
            </div>
        </div>
    </div>
    <script>
        //深度优先搜索
        let deepTraversall = (node, nodeList=[]) => {
            if(node != null){
                nodeList.push(node);
                let children = node.children;
                for(let i = 0; i < children.length;i ++){
                    deepTraversall(children[i] , nodeList);
                }
            }
            return nodeList;
        }

        let deepTraversall2 = (node) => {
            let nodes = [];
            if(node){
                nodes.push(node);
                let children = node.children;
                for(let i = 0;i < children.length;i ++){
                    nodes = nodes.concat(deepTraversall2(children[i]));
                }
            }
            return nodes;
        }

        //非递归
        let dsp = (node) => {
            let stack = []
            let nodes = []
            if(node){
                stack.push(node);
                while(stack.length){
                    let item = stack.pop();
                    let children = item.children;
                    nodes.push(item);
                    for(let i = children.length - 1;i >= 0;i --){
                        stack.push(children[i]);
                    }
                }
            }
            return nodes;
            
        }

        let parent = document.getElementsByClassName("parent")[0];

        console.log(deepTraversall(parent));
        console.log(deepTraversall2(parent));
        console.log(dsp(parent));

        //广度优先搜索
        let bfs = (node) => {
            let stack = []
            let nodes = []
            if(node){
                stack.push(node)
                while(stack.length){
                    let item = stack.shift();
                    let children = item.children;
                    nodes.push(item);
                    for(let i = 0;i < children.length;i ++){
                        stack.push(children[i]);
                    }
                }
            }
            return nodes;
        }
        console.log(bfs(parent));
    </script>
</body>
</html>